package com.yndsoft.jc.utils.selectphoto;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;


import com.yndsoft.jc.R;
import com.yndsoft.jc.activity.BaseActivity;
import com.yndsoft.jc.crop.Crop;
import com.yndsoft.jc.crop.util.FileUtils;
import com.yndsoft.jc.supplier.utils.ToastUtil;
import com.yndsoft.jc.utils.ConstantValues;
import com.yndsoft.jc.utils.permission.CheckPermission;
import com.yndsoft.jc.utils.permission.FilePhotoUtils;
import com.yndsoft.jc.utils.permission.PermissionActivity;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import butterknife.Bind;

import static com.yndsoft.jc.utils.ConstantValues.REQUEST_CODE;


public class SelectPhotoActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private ProgressDialog mProgressDialog;
    /**
     * 存储文件夹中的图片数量
     */
    private int mPicsSize;
    /**
     * 图片数量最多的文件夹
     */
    private File mImgDir;
    /**
     * 所有的图片
     */
    private List<String> mImgs = new ArrayList<String>();
    ;
    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<String>();

    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();

    @Bind(R.id.gv_select_photo)
    GridView gv_select_photo;
    @Bind(R.id.mback_tv)
    TextView mback_tv;
    @Bind(R.id.btn_count)
    Button btn_count;
    @Bind(R.id.tv_compeleted)
    TextView tv_compeleted;
    private SelectPhotoAdapter mAdapter;
    private boolean isSingle;
    private CheckPermission checkPermission;//检测权限器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_photo);
        checkPermission = CheckPermission.getInstance(this);
        if (null != getIntent()) {
            isSingle = getIntent().getBooleanExtra("IsSingle", false);
        }
        FilePhotoUtils.init();
        mTempDir = new File(FilePhotoUtils.getFileDir() + File.separator);
        if (!mTempDir.exists()) {
            mTempDir.mkdirs();
        }
        getImages();
        setListener();
    }

    /**
     * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

        new Thread(new Runnable() {
            @Override
            public void run() {

                String firstImage = null;

                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = SelectPhotoActivity.this
                        .getContentResolver();

                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);

                Log.e("TAG", mCursor.getCount() + "");
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));

                    Log.e("TAG", path);
                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;
                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    ImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new ImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }
                    String[] list = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg")
                                    || filename.endsWith(".png")
                                    || filename.endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    });

                    int picSize = 0;
                    if (null != list && list.length > 0) {
                        picSize = list.length;
                        imageFloder.setCount(picSize);
                        mImageFloders.add(imageFloder);
                    }


                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();

                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;

                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);

            }
        }).start();

    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mProgressDialog.dismiss();
            // 为View绑定数据
            data2View();
        }
    };

    //进入权限设置页面
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, REQUEST_CODE, ConstantValues.PERMISSION_COMMENT);
    }

    /**
     * 为View绑定数据
     */
    private void data2View() {

        mImgs.clear();
        for (int i = 0; i < mImageFloders.size(); i++) {
            List<String> strings = Arrays.asList(new File(mImageFloders.get(i).getDir()).list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                            || filename.endsWith(".jpeg"))
                        return true;
                    return false;
                }
            }));

            for (int j = 0; j < strings.size(); j++) {
                String dir = mImageFloders.get(i).getDir() + "/" + strings.get(j);
                mImgs.add(dir);
            }

        }
        if (mImgs.size() == 0) {
            Toast.makeText(this, "您的相册没有扫描到图片", Toast.LENGTH_LONG).show();
        }


        mAdapter = new SelectPhotoAdapter(this, mImgs);
        mAdapter.setSingle(isSingle);
        mAdapter.setTakePhoto(new SelectPhotoAdapter.TakePhoto() {
            @Override
            public void takePhoto() {
                if (checkPermission.permissionSet(ConstantValues.PERMISSION_COMMENT)) {
                    startPermissionActivity();
                } else {
                    getImageFromCamera();
                }
            }

            @Override
            public void selectedCounts(int count) {
                if (count > 0) {
                    btn_count.setVisibility(View.VISIBLE);
                    btn_count.setText(count + "");
                } else {
                    btn_count.setVisibility(View.GONE);
                }
            }
        });
        gv_select_photo.setAdapter(mAdapter);
        gv_select_photo.setOnItemClickListener(this);
        mAdapter.notifyDataSetChanged();

    }

    private File mTempDir;
    private String mCurrentPhotoPath;
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1458;

    protected void getImageFromCamera() {

        String fileName = "Temp_camera" + String.valueOf(System.currentTimeMillis());
        File cropFile = new File(mTempDir, fileName);
        Uri fileUri = Uri.fromFile(cropFile);
        mCurrentPhotoPath = fileUri.getPath();
        FilePhotoUtils.startActionCapture(this, cropFile, REQUEST_CODE_CAPTURE_CAMEIA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
                System.out.println(" REQUEST_CODE_CAPTURE_CAMEIA " + mCurrentPhotoPath);
                if (mCurrentPhotoPath != null) {
                    beginCrop(Uri.fromFile(new File(mCurrentPhotoPath)));
                }
            } else if (requestCode == Crop.REQUEST_CROP) {
                handleCrop(resultCode, data);
            } else if (requestCode == SELECT_BIG_IMG_CODE) {
                Intent intent = getIntent();
                intent.putExtra("mImgUrl", data.getStringExtra("mImgUrl"));
                setResult(RESULT_OK, intent);
                finish();
            }
        } else if (resultCode == PermissionActivity.PERMISSION_GRANTED) {
            getImageFromCamera();
        }
    }

    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis());
        File cropFile = new File(mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).setCropType(true).start(this);
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            UploadResponse uploadResponse = new UploadResponse();
            uploadResponse.setUrl(Crop.getOutput(result).getPath());
            setResult(uploadResponse);

        } else if (resultCode == Crop.RESULT_ERROR) {
            Toast.makeText(this, Crop.getError(result).getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    public void setListener() {
        mback_tv.setOnClickListener(this);
        tv_compeleted.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTempDir.exists()) {
            FileUtils.deleteFile(mTempDir);
        }
    }

    public static final int SELECT_BIG_IMG_CODE = 10001;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, BigImageActivity.class);
        intent.putStringArrayListExtra("mImgs", (ArrayList<String>) mImgs);
        intent.putExtra("position", position - 1);
        startActivityForResult(intent, SELECT_BIG_IMG_CODE);
    }

    Intent intent;

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.mback_tv:
                finish();
                break;
            case R.id.tv_compeleted:
                if (null != SelectPhotoAdapter.getmSelectedImage() && SelectPhotoAdapter.getmSelectedImage().size() > 0) {
                    if (isSingle) {
                        UploadResponse uploadResponse = new UploadResponse();
                        uploadResponse.setUrl(SelectPhotoAdapter.getmSelectedImage().get(0));
                        setResult(uploadResponse);
                    } else {
                        setResult("");
                    }
                } else {
                    ToastUtil.show(mContext, "请先选择图片");
                }
                break;
        }
    }

    private <T> void setResult(T t) {
        intent = getIntent();
        if (isSingle) {
            if (t instanceof UploadResponse) {
                intent.putExtra("mImgUrl", ((UploadResponse) t).getUrl());
            }

        } else {
            List<String> urls = SelectPhotoAdapter.getmSelectedImage();
            String[] mUrls = new String[urls.size()];
            for (int i = 0; i < urls.size(); i++) {
                mUrls[i] = urls.get(i);
            }
            intent.putExtra("mImgUrl", mUrls);
        }
        setResult(RESULT_OK, intent);
        finish();
    }
}
